const Router = require("@koa/router");
const { news, ObjectId } = require("../models/mongo");
const { bodyParser } = require("@koa/bodyparser");

const router = new Router({
    prefix: "/api",
});

router.get("/blog", async (ctx) => {
    const count = await news.countDocuments();
    const newsResult = await news.aggregate([
        {
            $lookup: {
                from: "users",
                localField: "author_id",
                foreignField: "_id",
                as: "author",
            },
        },
    ])

        .toArray();
    ctx.body = { newsResult };

});

// 删除
router.post("/delBlog", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delBlog = await news.deleteOne({ _id: new ObjectId(id) })

    if (delBlog) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 修改
router.post("/updateBlog", bodyParser(), async (ctx) => {
    const { id, title, publishedAt, uptime, p_1, p_2, url_1, url_2 } = ctx.request.body;
    const modifyBlog = await news.updateOne({ _id: new ObjectId(id) }, {
        $set: { id, title, publishedAt, uptime, p_1, p_2, url_1, url_2 },
    })

    if (modifyBlog) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 添加
router.post("/addBlog", bodyParser(), async (ctx) => {
    const { title, publishedAt, uptime, auname, p_1, p_2, url_1, url_2 } = ctx.request.body;
    const addBlogRes = await news.insertOne({ title, publishedAt, uptime, auname, p_1, p_2, url_1, url_2 })

    if (addBlogRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});

// 查询
router.post("/selectnews", bodyParser(), async (ctx) => {
    const { filterQuery } = ctx.request.body;
    const total = await news.countDocuments();
    const list = await news.find(filterQuery).toArray()
    ctx.body = {
        code: 200,
        message: "success",
        total,
        list,
    };
});


// 浏览量
router.post("/addView_Num", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    console.log(id);
    const addViewNum = await news.updateOne({ _id: new ObjectId(id) }, {
        $inc: { view_num: 1 },
    })

    if (addViewNum) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});
module.exports = router;
